<?php

namespace Admin\Models\overt;

use Helpers\Cache;
use Phalcon\Mvc\Model;

class XhovertAreainfo extends Model
{

    /**
     *
     * @var integer
     * @Primary
     * @Column(type="integer", length=11, nullable=false)
     */
    public $areaCode;

    /**
     *
     * @var string
     * @Column(type="string", length=50, nullable=true)
     */
    public $areaName;

    /**
     *
     * @var integer
     * @Column(type="integer", length=11, nullable=true)
     */
    public $parentCode;

    /**
     *
     * @var integer
     * @Column(type="integer", length=11, nullable=true)
     */
    public $areaLevel;

    /**
     *
     * @var integer
     * @Column(type="integer", length=11, nullable=true)
     */
    public $sort;

    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        $this->setSchema("xh_webmanage");
    }

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'XHOvert_AreaInfo';
    }

    public function columnMap()
    {
        return [
            'iAreaCode'     => 'areaCode',
            'sAreaName'     => 'areaName',
            'iParentCode'   => 'parentCode',
            'iAreaLevel'    => 'areaLevel',
            'iSort'         => 'sort',
        ];
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhovertAreainfo[]|XhovertAreainfo
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhovertAreainfo
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    /**
     * 根据地区父id获取子地区列表
     *
     * @param int $parentCode
     * @return array|bool|mixed|null
     *
     * create by ck 20170815
     */
    public static function getChildArea($parentCode = 0)
    {
        $cacheName = 'area_code_' . $parentCode;
        if(Cache::exists($cacheName)) {
            return Cache::get($cacheName);
        }
        $areaList = self::find([
            'conditions' => 'parentCode = :parentCode:',
            'bind' => ['parentCode' => $parentCode],
            'order' => 'sort'
        ])->toArray();
        Cache::save($cacheName, $areaList);
        return $areaList;
    }

    /**
     * 通过code获取地区名
     *
     * @param $code
     * @return bool|Model\Resultset|\Phalcon\Mvc\Phalcon\Mvc\Model
     *
     * create by sqb 20181219
     */
    public static function getNameByCode($code)
    {
        $info = self::findFirst($code);
        if ($info) {
            return $info->areaName;
        }

        return false;
    }
}
